import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { Button, Card, DatePicker, Icon, message, Radio, Table } from 'antd';

import TreeMultiSelect from '@/components/TreeMultiSelect';
import EchartsLine from '@/components/Dashboard/EchartsLine';

const { RangePicker } = DatePicker;

class HistoryCard extends Component {

  constructor(props) {
    super(props);
    this.extra = (
      <Button type='primary' onClick={() => this.searchData()}>
        <Icon type='search'/>Search
      </Button>
    );
    this.columns = [{
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: '30%',
    }, {
      title: 'Time',
      dataIndex: 'time',
      key: 'time',
      width: '35%',
    }, {
      title: 'Value',
      dataIndex: 'value',
      key: 'value',
      width: '35%',
    }];
    this.state = {
      showType: 'line',
      searchParams: [],
      treeSelectValue: [],
      rangePickerValue: []
    };
  }

  searchData = () => {
    const { treeSelectValue, rangePickerValue, showType } = this.state;
    if(!treeSelectValue || treeSelectValue.length===0) {
      message.error('Please select history search parameter!');
    } else {
      const h = (typeof treeSelectValue)==='string'?treeSelectValue:treeSelectValue.join('|||');
      const payload = {h, pageNo:showType==='line'?-1:1};
      if(rangePickerValue && rangePickerValue.length === 2) {
        payload.start = rangePickerValue[0].format('YYYY-MM-DD HH:mm:ss');
        payload.end = rangePickerValue[1].format('YYYY-MM-DD HH:mm:ss');
      }
      this.props.dispatch({type: 'historyData/fetch', payload});
    }
  }

  handlePageChange = (changePageNo) => {
    const { pageNo, dispatch } = this.props;
    if (changePageNo !== pageNo) {
      dispatch({ type: 'historyData/fetch', payload: { pageNo: changePageNo } });
    }
  };

  initSearchParams = (searchParams) => (searchParams.map((searchParam)=> {
    if(searchParam.children) {
      searchParam.selectable = false;
      searchParam.children = searchParam.children.map((item)=>({
        title: item.title,
        value: item.title+'||'+item.historyOrd,
        key: item.key
      }));
      return searchParam;
    } else {
      return {
        title: searchParam.title,
        value: searchParam.title+'||'+searchParam.historyOrd,
        key: searchParam.key
      }
    }
  }));

  componentDidMount() {
    this.setState({
      showType: 'line',
      searchParams: this.initSearchParams(this.props.searchParams),
      treeSelectValue: [],
      rangePickerValue: []
    })
  }

  componentDidUpdate() {
    const { name, list } = this.props;
    const datas = list.map((arr)=>arr.map((data)=>([data.time, data.value])));
    if(this.state.showType === 'line' && this.echartsLine) {
      this.echartsLine.updateChart(name, datas);
    }
  }

  componentWillReceiveProps(nextProps) {
    if(nextProps.searchParams !== this.props.searchParams) {
      this.props.searchParams = nextProps.searchParams;
      this.setState({
        showType: 'line',
        searchParams: this.initSearchParams(this.props.searchParams),
        treeSelectValue: [],
        rangePickerValue: []
      });
    }
  }

  render() {
    const { name, list, total, pageNo, pageSize, loading } = this.props;
    const { showType, searchParams, treeSelectValue, rangePickerValue } = this.state;
    const title = (
      <span>
        <Radio.Group value={showType}
                     buttonStyle='solid'
                     onChange={event=>this.setState({showType: event.target.value})}>
          <Radio.Button value='line'><Icon type='line-chart' /></Radio.Button>
          <Radio.Button value='table'><Icon type='table' /></Radio.Button>
        </Radio.Group>
        <TreeMultiSelect
          style={{margin: '0 10px', width: 300}}
          value={treeSelectValue}
          treeData={searchParams}
          onChange={treeSelectValue=>this.setState({treeSelectValue})}
          placeholder='Please select history search parameter'
          // multiple={showType==='line'}
          // treeCheckable={showType==='line'}
        />
        <RangePicker
          style={{margin: '0 10px'}}
          value={rangePickerValue}
          showTime={{ format: 'HH:mm' }}
          format='YYYY-MM-DD HH:mm'
          placeholder={['Start Time', 'End Time']}
          onChange={rangePickerValue=>this.setState({rangePickerValue})}
        />
      </span>
    );
    let dom = '';
    if(showType==='table') {
      dom = (<Table
          className={'table-wrapper'}
          columns={this.columns}
          dataSource={list[0]}
          rowKey='_id'
          loading={loading}
          pagination={{
            total: total,
            pageSize: pageSize,
            current: pageNo,
            onChange: this.handlePageChange,
          }}
        />);
    } else {
      const datas = list.map((arr)=>arr.map((data)=>([data.time, data.value])));
      dom = (<EchartsLine ref={(e)=>{this.echartsLine = e}}  title='Search Result' legends={name} datas={datas}/>)
    }
    return (
      <Card title={title} extra={this.extra}>{dom}</Card>
    );
  }
}

HistoryCard.propTypes = {
  searchParams: PropTypes.array.isRequired
}

export default connect(({ historyData, loading }) => ({
  ...historyData,
  loading: loading.effects['historyData/fetch'],
}))(HistoryCard);
